package com.xuhao.examai.interfaces.controllers;

import com.xuhao.examai.domain.models.User;
import com.xuhao.examai.application.services.UserService;
import com.xuhao.examai.application.dto.UserDTO;
import com.xuhao.examai.common.ResultVO;
import com.xuhao.examai.common.PageResult;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Tag(name = "用户管理", description = "用户相关API")
@RestController
@RequestMapping("/api/users")
@RequiredArgsConstructor
public class UserController {

	private final UserService userService;

	@Operation(summary = "用户注册")
	@PostMapping("/register")
	public ResultVO<User> register(@Valid @RequestBody UserDTO userDTO) {
		User user = convertToEntity(userDTO);
		return ResultVO.success(userService.register(user));
	}

	@Operation(summary = "获取当前用户信息")
	@GetMapping("/me")
	public ResultVO<User> getCurrentUser(@AuthenticationPrincipal User user) {
		return ResultVO.success(user);
	}

	@Operation(summary = "更新个人信息")
	@PutMapping("/me")
	public ResultVO<User> updateProfile(@AuthenticationPrincipal User user, @Valid @RequestBody UserDTO userDTO) {
		User updateUser = convertToEntity(userDTO);
		updateUser.setId(user.getId());
		return ResultVO.success(userService.updateProfile(updateUser));
	}

	@Operation(summary = "获取用户详情")
	@GetMapping("/{id}")
	public ResultVO<User> getUserById(@PathVariable Long id) {
		return ResultVO.success(userService.getUserById(id));
	}

	@Operation(summary = "分页查询用户")
	@GetMapping
	public ResultVO<PageResult<User>> getUsersByPage(
			@RequestParam(defaultValue = "1") Integer current,
			@RequestParam(defaultValue = "10") Integer size,
			@RequestParam(required = false) String keyword,
			@RequestParam(required = false) String role) {
		return ResultVO.success(userService.getUsersByPage(current, size, keyword, role));
	}

	@Operation(summary = "根据角色获取用户")
	@GetMapping("/role/{role}")
	public ResultVO<List<User>> getUsersByRole(@PathVariable String role) {
		try {
			User.Role userRole = User.Role.valueOf(role.toUpperCase());
			return ResultVO.success(userService.getUsersByRole(userRole));
		} catch (IllegalArgumentException e) {
			return ResultVO.error("无效的角色: " + role);
		}
	}

	@Operation(summary = "更新用户角色")
	@PutMapping("/{userId}/role")
	public ResultVO<User> updateRole(@PathVariable Long userId, @RequestParam String role) {
		try {
			User.Role userRole = User.Role.valueOf(role.toUpperCase());
			return ResultVO.success(userService.updateRole(userId, userRole));
		} catch (IllegalArgumentException e) {
			return ResultVO.error("无效的角色: " + role);
		}
	}

	@Operation(summary = "切换用户状态")
	@PutMapping("/{userId}/status")
	public ResultVO<User> toggleUserStatus(@PathVariable Long userId) {
		return ResultVO.success(userService.toggleUserStatus(userId));
	}

	@Operation(summary = "重置用户密码")
	@PutMapping("/{userId}/password")
	public ResultVO<User> resetPassword(@PathVariable Long userId, @RequestParam String newPassword) {
		return ResultVO.success(userService.resetPassword(userId, newPassword));
	}

	@Operation(summary = "更新用户头像")
	@PutMapping("/{userId}/avatar")
	public ResultVO<User> updateAvatar(@PathVariable Long userId, @RequestParam String avatarUrl) {
		return ResultVO.success(userService.updateAvatar(userId, avatarUrl));
	}

	@Operation(summary = "检查用户名是否存在")
	@GetMapping("/check-username")
	public ResultVO<Boolean> checkUsername(@RequestParam String username) {
		return ResultVO.success(userService.existsByUsername(username));
	}

	@Operation(summary = "检查邮箱是否存在")
	@GetMapping("/check-email")
	public ResultVO<Boolean> checkEmail(@RequestParam String email) {
		return ResultVO.success(userService.existsByEmail(email));
	}

	@Operation(summary = "删除用户")
	@DeleteMapping("/{id}")
	public ResultVO<Void> deleteUser(@PathVariable Long id) {
		userService.deleteUser(id);
		return ResultVO.success();
	}

	/**
	 * 将DTO转换为实体
	 */
	private User convertToEntity(UserDTO dto) {
		User user = new User();
		user.setId(dto.getId());
		user.setUsername(dto.getUsername());
		user.setPassword(dto.getPassword());
		user.setName(dto.getName());
		user.setEmail(dto.getEmail());
		user.setRole(dto.getRole());
		user.setPhone(dto.getPhone());
		user.setAvatar(dto.getAvatar());
		user.setIsActive(dto.getIsActive());
		return user;
	}
}
